<?php
/**
 * @description  :   实现利用DNSPOD动态更改域名指向，可以实现家用拨号上网电脑也可一当作广域网服务器
 * @author       :   sang.williams@gmail.com
 * @time         :   2013-8-6   
 *
 * @todo         :
 *
 *  revision:
 *      2013-11-21  
 *          增加了登录验证
 *          修改了换行符
 **/


header("Content-type:text/html;charset=utf8");

require_once dirname(__file__).'/lib/conf.php';
require_once dirname(__file__).'/lib/verify.php';
require_once dirname(__file__).'/lib/changeRecord.php';

//验证用户名、密码
if (!verify()) {
    echo 'Login Error'.PHP_EOL;
    echo ' Becouse of Too many connect or invalid password.'.PHP_EOL;
    exit();
}

require_once dirname(__file__).'/lib/getDomainID.php';
require_once dirname(__file__).'/lib/getRecordID.php';
require_once dirname(__file__).'/lib/getPublicIP.php';
require_once dirname(__file__).'/lib/getRecordIP.php';
//获取域名ID
$domain_id = getDomainID(DOMAIN);

if (!$domain_id) {
    echo 'Can not find the domain in DNSPOD'.PHP_EOL;//域名未在DNSPOD添加,请在DNSPOD添加域名。
    exit();
}

//获取RECORD ID
$record_id= getRecordID($domain_id, RECORD);
if (!$record_id) {
    echo 'Can not find the record in DNSPOD'.PHP_EOL;//您当前还未在DNSPOD建立此record记录,请先前往DNSPOD添加记录。
    exit();
}

while(1){

	echo date("Y-m-d H:i:s").": ";

	$record_ip = getRecordIP($domain_id, RECORD);
	$ip = getPublicIP();
	
	//判断获取的公网IP地址是否合法
	if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)){
		echo 'Invalid Public IP: '.$ip.PHP_EOL;
		continue;
	}
	
	
	echo 'Current Record IP: '.$record_ip."_____";//当前record IP 为
	echo 'Public IP: '.$ip."_____";
	
	//如果当前广域网IP和DNSPOD注册IP不一样，则修改为当前广域网IP
	if ($ip != $record_ip) {
		echo 'A record is changed: '.PHP_EOL.changeRecord( $domain_id, $record_id, $ip, RECORD).PHP_EOL;
	}else{
		echo 'Nothing to do. '.PHP_EOL;
	}
	
	sleep(1800);
}
?>
